package cn.edu.zime.tjh.iotapp;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import cn.edu.zime.tjh.iotapp.api.ApiCallback;
import cn.edu.zime.tjh.iotapp.api.ApiService;
import cn.edu.zime.tjh.iotapp.utils.ImageUtils;
import de.hdodenhof.circleimageview.CircleImageView;

public class RegisterActivity extends AppCompatActivity {
    
    private static final String TAG = "RegisterActivity";

    private EditText etUsername, etPassword, etConfirmPassword, etEmail, etVerificationCode;
    private Button btnRegister, btnBack, btnSelectAvatar, btnGetCode;
    private CircleImageView ivAvatar;
    private TextView tvMessage;

    private ApiService apiService;
    private Uri avatarUri;
    private File avatarFile;
    private boolean hasCustomAvatar = false;
    
    // 图片选择结果处理器
    private ActivityResultLauncher<Intent> imagePickerLauncher;
    private ActivityResultLauncher<Intent> cameraLauncher;
    
    // 进度对话框
    private ProgressDialog progressDialog;
    
    // 添加验证码相关控件变量
    private boolean isCodeSent = false; // 跟踪验证码是否已发送
    private CountDownTimer countDownTimer; // 倒计时器
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化API服务
        apiService = ApiService.getInstance();

        // 初始化视图
        initViews();
        
        // 注册结果处理器
        registerResultLaunchers();
        
        // 设置按钮点击事件
        setupButtonListeners();
    }
    
    /**
     * 初始化视图组件
     */
    private void initViews() {
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        etEmail = findViewById(R.id.etEmail);
        btnRegister = findViewById(R.id.btnRegister);
        btnBack = findViewById(R.id.btnBack);
        btnSelectAvatar = findViewById(R.id.btnSelectAvatar);
        ivAvatar = findViewById(R.id.ivAvatar);
        tvMessage = findViewById(R.id.tvMessage);
        
        // 初始化进度对话框
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在处理...");
        progressDialog.setCancelable(false);
        
        etVerificationCode = findViewById(R.id.etVerificationCode);
        btnGetCode = findViewById(R.id.btnGetCode);
    }
    
    /**
     * 注册Activity结果处理器
     */
    private void registerResultLaunchers() {
        // 图片选择器结果处理
        imagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    avatarUri = result.getData().getData();
                    try {
                        processSelectedAvatar(avatarUri);
                    } catch (IOException e) {
                        Log.e(TAG, "处理选择的头像失败", e);
                        showMessage("处理头像失败: " + e.getMessage());
                    }
                }
            }
        );
        
        // 相机结果处理
        cameraLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    try {
                        processSelectedAvatar(avatarUri);
                    } catch (IOException e) {
                        Log.e(TAG, "处理拍摄的头像失败", e);
                        showMessage("处理头像失败: " + e.getMessage());
                    }
                }
            }
        );
    }
    
    /**
     * 设置按钮点击事件
     */
    private void setupButtonListeners() {
        // 注册按钮
        btnRegister.setOnClickListener(v -> {
            // 验证输入
            if (validateInput()) {
                // 提交注册
                register();
            }
        });
        
        // 返回按钮
        btnBack.setOnClickListener(v -> finish());
        
        // 选择头像按钮
        btnSelectAvatar.setOnClickListener(v -> showAvatarOptions());
        
        // 添加获取验证码按钮点击事件
        btnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = etEmail.getText().toString().trim();
                
                // 验证邮箱格式
                if (email.isEmpty()) {
                    showMessage("请输入电子邮箱");
                    return;
                }
                
                if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                    showMessage("请输入有效的电子邮箱地址");
                    return;
                }
                
                // 请求验证码
                requestVerificationCode(email);
            }
        });
    }
    
    /**
     * 显示头像选择选项
     */
    private void showAvatarOptions() {
        // 检查相机和存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            
            ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
                100);
            return;
        }
        
        String[] options = {"拍照", "从相册选择", "使用默认头像"};
        
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("选择头像");
        builder.setItems(options, (dialog, which) -> {
            switch (which) {
                case 0: // 拍照
                    takePicture();
                    break;
                case 1: // 从相册选择
                    pickImage();
                    break;
                case 2: // 使用默认头像
                    useDefaultAvatar();
                    break;
            }
        });
        builder.show();
    }
    
    /**
     * 打开相机拍照
     */
    private void takePicture() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        
        // 确保有相机应用处理Intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // 创建保存照片的File
            File photoFile = null;
            try {
                photoFile = ImageUtils.createTempImageFile(this, "avatar_");
                avatarFile = photoFile;
            } catch (IOException ex) {
                Log.e(TAG, "创建图片文件失败", ex);
                Toast.makeText(this, "创建图片文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 如果文件创建成功，继续拍照
            avatarUri = FileProvider.getUriForFile(this,
                    "cn.edu.zime.tjh.iotapp.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, avatarUri);
            cameraLauncher.launch(takePictureIntent);
        } else {
            Toast.makeText(this, "没有找到相机应用", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 从相册选择图片
     */
    private void pickImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        imagePickerLauncher.launch(intent);
    }
    
    /**
     * 使用默认头像
     */
    private void useDefaultAvatar() {
        hasCustomAvatar = false;
        ivAvatar.setImageResource(R.drawable.default_avatar);
        avatarUri = null;
        avatarFile = null;
        Toast.makeText(this, "将使用默认头像", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 处理选择的头像
     */
    private void processSelectedAvatar(Uri uri) throws IOException {
        // 检查URI是否为空
        if (uri == null) {
            showMessage("无效的头像文件");
            return;
        }
        
        // 压缩头像
        avatarFile = ImageUtils.compressImage(this, uri, true);
        
        // 显示头像到UI
        Bitmap bitmap = BitmapFactory.decodeFile(avatarFile.getAbsolutePath());
        ivAvatar.setImageBitmap(bitmap);
        
        // 标记为自定义头像
        hasCustomAvatar = true;
    }
    
    /**
     * 请求邮箱验证码
     */
    private void requestVerificationCode(String email) {
        progressDialog.setMessage("正在发送验证码...");
        progressDialog.show();
        
        // 调用API获取验证码
        apiService.getRegisterVerificationCode(email, new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    Toast.makeText(RegisterActivity.this, "验证码已发送到您的邮箱", Toast.LENGTH_LONG).show();
                    
                    // 标记验证码已发送
                    isCodeSent = true;
                    
                    // 启动倒计时
                    startCountDown();
                });
            }
            
            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "请求失败: " + errorMsg);
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    if (errorMsg.contains("connection")) {
                        showMessage("网络连接失败，请检查网络设置");
                    } else if (errorMsg.contains("timeout")) {
                        showMessage("请求超时，请稍后重试");
                    } else {
                        showMessage("操作失败: " + errorMsg);
                    }
                });
            }
        });
    }
    
    /**
     * 启动倒计时
     */
    private void startCountDown() {
        // 禁用按钮
        btnGetCode.setEnabled(false);
        
        // 60秒倒计时
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnGetCode.setText(millisUntilFinished / 1000 + "秒");
            }
            
            @Override
            public void onFinish() {
                btnGetCode.setText("重新获取");
                btnGetCode.setEnabled(true);
            }
        }.start();
    }
    
    /**
     * 验证用户输入
     */
    private boolean validateInput() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        
        // 验证用户名是否大于3位
        if (username.isEmpty()) {
            showMessage("请输入用户名");
            return false;
        }
        
        // 验证密码
        if (password.isEmpty()) {
            showMessage("请输入密码");
            return false;
        }
        
        if (password.length() < 6) {
            showMessage("密码长度不能少于6位");
            return false;
        }
        
        // 验证确认密码
        if (!password.equals(confirmPassword)) {
            showMessage("两次输入的密码不一致");
            return false;
        }
        
        // 验证邮箱
        if (email.isEmpty()) {
            showMessage("请输入电子邮箱");
            return false;
        }
        
        // 简单的邮箱格式验证
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            showMessage("请输入有效的电子邮箱地址");
            return false;
        }
        
        // 添加验证码验证
        if (!isCodeSent) {
            showMessage("请先获取验证码");
            return false;
        }
        
        String verificationCode = etVerificationCode.getText().toString().trim();
        if (verificationCode.isEmpty()) {
            showMessage("请输入验证码");
            return false;
        }
        
        return true;
    }
    
    /**
     * 显示消息
     */
    private void showMessage(String message) {
        tvMessage.setText(message);
        tvMessage.setVisibility(View.VISIBLE);
    }
    
    /**
     * 执行注册
     */
    private void register() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        String verificationCode = etVerificationCode.getText().toString().trim();
        
        progressDialog.setMessage("正在注册...");
        progressDialog.show();
        
        // 准备注册参数
        JSONObject registerParams = new JSONObject();
        try {
            registerParams.put("username", username);
            registerParams.put("password", password);
            registerParams.put("email", email);
            registerParams.put("verification_code", verificationCode);
            
            // 如果有自定义头像，直接转换为Base64并添加到请求参数中
            if (hasCustomAvatar && avatarFile != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(avatarFile.getAbsolutePath());
                String base64Avatar = "data:image/jpeg;base64," + ImageUtils.bitmapToBase64(bitmap);
                registerParams.put("avatar", base64Avatar);
            }
            
        } catch (JSONException e) {
            Log.e(TAG, "准备注册参数失败", e);
            progressDialog.dismiss();
            showMessage("准备注册参数失败: " + e.getMessage());
            return;
        }
        
        // 调用API注册
        performRegister(registerParams);
    }
    
    /**
     * 执行注册请求
     */
    private void performRegister(JSONObject registerParams) {
        // 调用API注册
        apiService.register(registerParams, new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                Log.d(TAG, "注册成功: " + response.toString());
                
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    
                    // 显示成功消息
                    Toast.makeText(RegisterActivity.this, "注册成功！请登录", Toast.LENGTH_LONG).show();
                    
                    // 返回登录界面
                    finish();
                });
            }

            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "请求失败: " + errorMsg);
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    if (errorMsg.contains("connection")) {
                        showMessage("网络连接失败，请检查网络设置");
                    } else if (errorMsg.contains("timeout")) {
                        showMessage("请求超时，请稍后重试");
                    } else {
                        showMessage("操作失败: " + errorMsg);
                    }
                });
            }
        });
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        
        // 取消倒计时
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("isCodeSent", isCodeSent);
        // 保存倒计时剩余时间
        if (countDownTimer != null) {
            // 这里需要额外记录倒计时开始时间和剩余时间
        }
        // 保存头像Uri和文件路径
        if (avatarUri != null) {
            outState.putString("avatarUri", avatarUri.toString());
        }
        if (avatarFile != null) {
            outState.putString("avatarFilePath", avatarFile.getAbsolutePath());
        }
        outState.putBoolean("hasCustomAvatar", hasCustomAvatar);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // 恢复状态
        if (savedInstanceState != null) {
            isCodeSent = savedInstanceState.getBoolean("isCodeSent", false);
            // 恢复头像等其他状态
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，显示头像选择对话框
                showAvatarOptions();
            } else {
                // 权限被拒绝
                Toast.makeText(this, "需要相机权限才能拍摄头像", Toast.LENGTH_SHORT).show();
            }
        }
    }
}